package com.seven.thread;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author sevenDay
 * @classname SevenRejectedExecutionHandler
 * @description: 超过线程池之后的处理策略
     * String message = "Task " + r.toString() +
    " rejected from " +
    executor.toString();
    SevenRunnableTask task = (SevenRunnableTask) r;
    LOGGER.error("报警信息: 任务ID {} , 任务名称: {} 被线程池拒绝了，没有执行...msg {}",task.getTaskId(),task.getTaskName(),message);
         }
 * @date 2017/11/16
 */
public abstract class  SevenRejectedExecutionHandler implements RejectedExecutionHandler {

    private ConcurrentHashMap<String,Object> taskContainer;

    public SevenRejectedExecutionHandler(SevenThreadPool instance){
        this.taskContainer =instance.getTaskContainer();
    }
    /**
     * 实现拒绝策略的措施,那么需要移除任务队列
     * @param r
     * @param executor
     */
    @Override
    public final void rejectedExecution(Runnable r, ThreadPoolExecutor executor){
        SevenFutureTask futureTask = (SevenFutureTask) r;
        Runnable runnable = futureTask.getRunnable();
        if (runnable instanceof SevenThread){
            SevenThread thread =  (SevenThread)runnable;
            String key = thread.getTaskId()+"  "+ thread.getTaskName();
            taskContainer.remove(key);
        }else if (runnable instanceof SevenRunnable){
            SevenRunnable thread =  (SevenRunnable)runnable;
            String key = thread.getTaskId()+"  "+ thread.getTaskName();
            taskContainer.remove(key);
        }else if (runnable instanceof SevenCallable){
            SevenCallable thread =  (SevenCallable)runnable;
            String key = thread.getTaskId()+"  "+ thread.getTaskName();
            taskContainer.remove(key);
        }
        rejectedTask(r,executor);
    }

    /**
     * 实现自己拒绝任务的处理方案
     * @param r
     * @param executor
     */
    public abstract void rejectedTask(Runnable r, ThreadPoolExecutor executor);

}
